<?php
declare(strict_types=1);
namespace app\core;

use think\facade\Config;
use Overtrue\Pinyin\Pinyin;
use think\facade\Request;
use think\facade\Db;

class Res
{
    public static $modelName='';
    /**
     * 数组取值
     */
    public static function kv($arr,$key,$var='')
    {
        if(is_array($arr)){
            if(array_key_exists($key,$arr) && $arr[$key]!==NULL && $arr[$key]!==''){
                return $arr[$key];
            }else{
                return $var;
            }
        }else{
            return $var;
        }
    }

    /**
     * 拼音
     */
    public static function Pinyin()
    {
        return new Pinyin();
    }

    /**
     * 拼音
     */
    public static function CnToPinyin($cn)
    {
        $res='';
        $model=new Pinyin();
        $list=$model->convert($cn, PINYIN_ASCII_TONE);
        if($list){
            foreach($list as $key=>$val){
                $res.=$val;
            }
        }
        return $res;
    }


    /**
     * 转为layui下拉框数据
     */
    public static function layuiOption($params)
    {
        $data=[];
        $i=0;
        foreach($params as $key=>$value){
            if($i==0){
                $data[]=['value'=>$value,'name'=>$value,'selected'=>true];
            }else{
                $data[]=['value'=>$value,'name'=>$value];
            }
            $i++;
        }
        return $data;
    }

    /**
     * 排序
     */
    public static function orderby($model,$params)
    {
        $field=self::kv($params,'field');
        $order=self::kv($params,'order');
        
        if($field=='' || $order==''){
            $field='id';
            $order='DESC';
        }
        
        if($field!='' && $order!=''){
            $model=$model->order($field,$order);
        }
        return $model;
    }

    /**
     * 列表分页
     * @param $params  参数
     * @param $model   表模型
     * @return $data
     */
    public static function page($model,$params)
    {
        $model=self::orderby($model,$params);

        $data=[];
        $limit = (int)self::kv($params,'limit',50);
        $total =$model->count();
        $last_page=ceil($total/$limit);
        $page=(int)self::kv($params,'page',1);
        if($page<1){
            $page=1;
        }
        if($page>$last_page){
            $page=1;
        }
        $offset = ($page-1)*$limit;

        $list = $model->limit($offset,$limit)->select();
        $data['data']=$list;
        $data['total']=$total;
        $data['current_page']=$page;
        $data['last_page']=$last_page;
        $data['per_page']=$limit;
        return $data;
    }

   

    /**
     * 配置列表
     */
    public static function getConfig($cfgName,$key='',$value='')
    {
        $list= Config::get($cfgName);
        return self::keyValue($list,$key,$value);
    }


    public static function keyValue($list,$key='',$value=''){
        if($key!==''){
            return self::kv($list,$key,$value);
        }else{
            return $list;
        }
    }



    public static function layList($list,$key='ym@maget',$value=''){
        if($key!='ym@maget'){
            $laylist=[];
            foreach($list as $k=>$v){
                $laylist[$k]=$v;
                $laylist[$v]=$k;
            }
            return self::kv($laylist,$key,$value);
        }else{
            return $list;
        }
    }

    
    /**
     * 获取登录信息
     * ["id"]=>int(23)["cp_id"]=>int(3)["sub_cp_id"]=>int(0)["login_name"]=>string(2)"CL"["is_admin"]=>int(0)
     */
    public static function loginInfo($key='id')
    {
        $admin = session('admin_info');
        return self::kv($admin,$key);
    }


    /**
     * 选择数据
     */
    public static function querymap($model,$map=[],$field=[],$params=[]){
        $options=self::columns($model);
       // $cp_id=Res::loginInfo('cp_id');
       // $sub_cp_id=Res::loginInfo('sub_cp_id');
       // $map[] = ['cp_id','=',$cp_id];
       // $map[] = ['sub_cp_id','=',$sub_cp_id];
        //$map[] = ['is_temp','=',0];  //临时客户 1 
        $map[] = ['is_deled','=',0];
        $map=self::fieldmap($map,$field,$params);
        $remap=[];
        foreach($map as $item){
            if(self::kv($options,self::kv($item,0))!=''){
                $remap[]=$item;
            }
        }
        return $remap;
    }

    public static function fieldmap($map=[],$field=[],$params=[]){
        if($field && $params){
            foreach($field as $key=>$value){
                if(isset($params[$key]) && $params[$key]!=''){
                    if($value=='like'){
                        $map[]=[$key,$value,"%".$params[$key]."%"];
                    }else{
                        $map[]=[$key,$value,$params[$key]];
                    }
                }
            }
            
        }
        return $map;
    }

    /**
     * 保存数据
     */
    public static function saveData($model,$data){
        $options=self::columns($model);

        $data['cp_id']=Res::loginInfo('cp_id');
        $data['user_id']=Res::loginInfo('id');
        $data['user_name']=Res::loginInfo('login_name');

        $reData=[];
        foreach($options as $key=>$value){
            if(self::kv($data,$key)!=='' && $key!='id'){  ///isset($data[$key]) 
                $reData[$key]=self::kv($data,$key);
            }
        }
        
        return $reData;
    }

    /**
     * 移除数据
     */
    public static function unsetData($data){
        $reData=$data;
        unset($reData['user_id']);
        unset($reData['user_name']);
        unset($reData['id']);
        return $reData;
    }

    public static function upModelData($tmodel,$upData,$field=[]){
        $tableName=$tmodel->getTable();
        $model=Relation::getModel($tableName);
        $map=[];
        foreach($field as $key=>$v){
            $map[]=[$key,'=',$v];
        }

        try {
            $saveData=self::saveData($model,$upData);
            $saveData=self::unsetData($saveData);
            $map=self::querymap($model,$map);
            $model->where($map)->update($saveData);
            return  true;
            
        }catch (\PDOException $e){
            return false;
        }
        
    }

    public static function saveModelData($tmodel,$upData,$field=[],$sel=''){
        $tableName=$tmodel->getTable();
        $model=Relation::getModel($tableName);
        $findRow=self::findField($model,$field,$sel);
        try {
            if($findRow['isadd']==true){
                $upData['cdate']=date('Y-m-d H:i:s');
                $saveData=Res::saveData($model,$upData);
                unset($saveData['id']);
                $id=$model->insertGetId($saveData);
                return  $id;
            }else{
                $saveData=Res::saveData($model,$upData);
                $saveData=Res::unsetData($saveData);
                $map =$findRow['map'];
                //$map=Res::querymap($model,$map);
                $model->where($map)->update($saveData);
                return  $findRow['id'];
            }
        }catch (\PDOException $e){
            return 0;
        }
        
    }

    public static function findField($tmodel,$field=[],$sel='*'){
        $tableName=$tmodel->getTable();
        $model=Relation::getModel($tableName);
        $reData=[];
        $data=[];
        $isadd=true;
        $id=0;
        $map=[];
        foreach($field as $key=>$v){
            $map[]=[$key,'=',$v];
        }
        if($sel==''){
            $sel='id';
        }
        $map=Res::querymap($model,$map);
        
        $res= $model->where($map)->field($sel)->find();
        if($res){
            $id=self::kv($res,'id',0);
            $isadd=false;
            $data=$res;
        }
        $reData=[
            'map'=>$map,
            'isadd'=>$isadd,
            'id'=>$id,
            'data'=>$data
        ];
        return $reData;
    }

    public static function findData($tmodel,$field=[],$sel='*'){
        $tableName=$tmodel->getTable();
        $model=Relation::getModel($tableName);
        $map=[];
        foreach($field as $key=>$v){
            $map[]=[$key,'=',$v];
        }
        if($sel==''){
            $sel='id';
        }
        $map=Res::querymap($model,$map);
        
        return $model->where($map)->field($sel)->find();
    }

    public static function allData($tmodel,$field=[],$sel='*'){
        $tableName=$tmodel->getTable();
        $model=Relation::getModel($tableName);
        $map=[];
        foreach($field as $key=>$v){
            $map[]=[$key,'=',$v];
        }
        if($sel==''){
            $sel='id';
        }
        $map=Res::querymap($model,$map);
        
        return $model->where($map)->field($sel)->select();
    }

    public static function allTableData($tableName,$field=[],$sel='*'){
        $model=Relation::getModel($tableName);
        $map=[];
        foreach($field as $key=>$v){
            $map[]=[$key,'=',$v];
        }
        if($sel==''){
            $sel='id';
        }
        $map=Res::querymap($model,$map);
        
        return $model->where($map)->field($sel)->select();
    }

    public static function findTableData($tableName,$field=[],$sel='*'){
        $model=Relation::getModel($tableName);
        $map=[];
        foreach($field as $key=>$v){
            $map[]=[$key,'=',$v];
        }
        if($sel==''){
            $sel='id';
        }
        $map=Res::querymap($model,$map);
        
        return $model->where($map)->field($sel)->find();
    }


    //获取数据的IDS
    public static function getIds($data,$key='id'){
        $ids='';
        if($data){
            $tmp=[];
            foreach($data as $items){
                $tmp[]=self::kv($items,$key);
            }
            $ids=implode(',',$tmp);
        }
        return $ids;
    }

    //通过IDS获取表数据
    public static function getDataByIds($table,$map,$field='id'){
        $model=Relation::getModel($table);
        $map=self::querymap($model,$map);
        $data=$model->where($map)->field($field)->select();
        return $data;
    }

    public static function columns($model){
        $name=$model->getTable();
        $list=self::getCache($name,36);
        if(!$list){
            $list=$model->getFields();
            self::setCache($name,$list);
        }
        //self::dChange($list);
        //self::layTableField($list);
        $data=[];
        foreach($list as $key=>$items){
            $data[$key]=($items['comment']!='')?$items['comment']:'没定义';
        }
        return $data;
    }

    public static function dChange($list){
        $str='[';
        foreach($list as $key=>$items){
            $str.='["'.$key.'","'.$items['comment'].'"],'.PHP_EOL;
        }
        $str.=']';
        echo $str;
    }

    public static function layTableField($list){
        $str='';
        foreach($list as $key=>$items){
            $str.='"'.$key.'":"",'.PHP_EOL;
        }
        echo $str;
    }

    //获取登录员工信息
    public static function getWorkerInfo($key=''){
        $user_id=self::loginInfo('id');
        $table='base_company_workers';
        $kname=$user_id.$table;
        $list=self::getCache($kname);
        if(!$list){
            $model=Relation::getModel($table);
            $map[] =['user_id','=',$user_id];
            $list=$model->where($map)->find();
            self::setCache($kname,$list);
        }
        if($key!=''){
            return self::kv($list,$key);
        }else{
            return $list;
        }
    }

    public static function getWordPath($table,$id){
        $dir='upload/attach/'.Res::loginInfo('cp_id').'/doc/'.$table;
        $path= app()->getRootPath().'public/'.$dir;
        $model=new File();
        $model->setPath($path);
        $data=[
            'pathdoc'=>$path.'/'.$id.'.docx',
            'pathpdf'=>$path.'/'.$id.'.pdf',
            'urldoc'=>$dir.'/'.$id.'.docx',
            'urlpdf'=>$dir.'/'.$id.'.pdf',
        ];
        return $data;
    }

    public static function showWordPath($table,$id){
        $pathData=self::getWordPath($table,$id);

        $outdoc=$pathData['pathdoc'];
        $outpdf=$pathData['pathpdf'];
        $data=[
            'urldoc'=>'',
            'urlpdf'=>'',
        ];
        if(file_exists($outdoc)){
            $data['urldoc']=Request::domain().'/'.$pathData['urldoc'];
        }
        if(file_exists($outpdf)){
            $data['urlpdf']=Request::domain().'/'.$pathData['urlpdf'];
        }
        return  ['code'=>1,'msg'=>'文档正在生成中...','data'=>$data];
    }

    public static function getXlsPath($fn='print'){
        $dir='upload/attach/'.Res::loginInfo('cp_id').'/xls';
        $path= app()->getRootPath().'public/'.$dir;
        $model=new File();
        $model->setPath($path);
        $data=[
            'pathxls'=>$path.'/'.$fn.'.xls',
            'pathpdf'=>$path.'/'.$fn.'.pdf',
            'urlxls'=>$dir.'/'.$fn.'.xls',
            'urlpdf'=>$dir.'/'.$fn.'.pdf',
        ];
        return $data;
    }

    public static function getCache($name,$outtime=100000000){
        $model=new File();
        return $model->getCache($name,$outtime);
    }

    public static function setCache($name,$arr){
        $model=new File();
        $model->setCache($name,$arr);
    }

    public static function Log($str){
        $model=new File();
        $model->Log($str);
    }

}